//
//  Fraction.m
//  02-ClassAndObject
//
//  Created by dllo on 16/7/5.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "Fraction.h"

@implementation Fraction

- (instancetype)initWithNumerator:(NSInteger)numerator denominator:(NSInteger)denominator {
    self = [super init];
    if (self) {
        _numerator = numerator;
        _denominator = denominator;
    }
    return self;
}

+ (instancetype)fractionWithNumerator:(NSInteger)numerator denominator:(NSInteger)denominator {
    return [[[Fraction alloc]initWithNumerator:numerator denominator:denominator] autorelease];
}

- (Fraction *)reduce {
    NSInteger a = self.numerator;
    NSInteger b = self.denominator;
    NSInteger c = a % b;
    if (c) {
        a = b;
        b = c;
        c = a % b;
    }
    self.numerator /= b;
    self.denominator /= b;
    Fraction *newFraction = [Fraction fractionWithNumerator:self.numerator denominator:self.denominator];
    return newFraction;
}

- (void)output {
    NSLog(@"%ld / %ld",self.numerator,self.denominator);
}

- (Fraction *)addFraction:(Fraction *)fraction {
    NSInteger newNum = self.numerator * fraction.denominator + self.denominator * fraction.numerator;
    
    NSInteger newDeno = self.denominator * fraction.denominator;
    
    Fraction *newFraction = [Fraction fractionWithNumerator:newNum denominator:newDeno];
    
    return [newFraction reduce];
    
}

- (Fraction *)subFraction:(Fraction *)fraction {
    NSInteger newNum = self.numerator * fraction.denominator - self.denominator * fraction.numerator;
    NSInteger newDeno = self.denominator * fraction.denominator;
    
    Fraction *newFraction = [Fraction fractionWithNumerator:newNum denominator:newDeno];
    return [newFraction reduce];
}

- (Fraction *)mulFraction:(Fraction *)fraction {
    NSInteger newNum = self.numerator * fraction.numerator;
    NSInteger newDeno = self.denominator * fraction.denominator;
    
    Fraction *newFraction = [Fraction fractionWithNumerator:newNum denominator:newDeno];
    return [newFraction reduce];
}

- (Fraction *)divFraction:(Fraction *)fraction {
    NSInteger newNum = self.numerator * fraction.denominator;
    NSInteger newDeno = self.denominator * fraction.numerator;
    
    Fraction *newFraction = [Fraction fractionWithNumerator:newNum denominator:newDeno];
    return [newFraction reduce];
}

- (void)compare:(Fraction *)fraction {
    if ([self subFraction:fraction] > 0) {
        NSLog(@"第一个数比第二个数大");
    } else if ([self subFraction:fraction] < 0) {
        NSLog(@"第一个数比第二个数小");
    } else {
          NSLog(@"相等");
    }
}

@end
